package com.orchard.orchardfarmmanagementsystem.pojo;

import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;

import java.util.Collection;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class CustomUserDetails extends User {

    private final Integer id;
    private final Set<String> permissions;
    private final Set<String> roles;

    public CustomUserDetails(
            com.orchard.orchardfarmmanagementsystem.entity.User user,
            Set<String> permissions,
            Set<String> roles) {
        super(user.getUsername(), user.getPassword(), mapAuthorities(permissions, roles));
        this.id = user.getUserId();
        this.permissions = permissions;
        this.roles = roles;
    }

    private static Collection<? extends GrantedAuthority> mapAuthorities(
            Set<String> permissions, Set<String> roles) {
        // 将角色添加 'ROLE_' 前缀
        Set<String> roleNames = roles.stream()
                .map(role -> "ROLE_" + role)
                .collect(Collectors.toSet());

        // 合并角色和权限，并转换为 GrantedAuthority
        return Stream.concat(
                roleNames.stream().map(SimpleGrantedAuthority::new),
                permissions.stream().map(SimpleGrantedAuthority::new)
        ).collect(Collectors.toList());
    }

    public Integer getId() {
        return id;
    }

    public Set<String> getPermissions() {
        return permissions;
    }

    public Set<String> getRoles() {
        return roles;
    }
}